package com.tommyb.util.gc
{
	/*************************************************************************
	 * 
	 * http://code.google.com/p/flex-uicomponent-cleaner-and-gc-initiator/
	 *
	 * GarbageCollectionInitiator class v1.0
	 * 
	 * The GarbageCollectionInitiator class is a static utility class used to
	 * execute the Flash Player garbage collection process.  The functionality
	 * implemented in this class is based on research conducted by Sean
	 * Christmann.  He documented his findings at
	 * http://www.craftymind.com/2008/04/09/kick-starting-the-garbage-collector-in-actionscript-3-with-air/ 
	 * 
	 *************************************************************************
	 * 
	 * Copyright (C) 2011 by Tommy Baggett 
	 * (http://www.linkedin.com/in/tommybaggett), Ansuria Solutions LLC
	 * 
	 * Permission is hereby granted, free of charge, to any person obtaining a
	 * copy of this software and associated documentation files (the 
	 * "Software"), to deal in the Software without restriction, including 
	 * without limitation the rights to use, copy, modify, merge, publish, 
	 * distribute, sublicense, and/or sell copies of the Software, and to 
	 * permit persons to whom the Software is furnished to do so, subject to 
	 * the following conditions:
	 * 
	 * The above copyright notice and this permission notice shall be included 
	 * in all copies or substantial portions of the Software.
	 * 
	 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
	 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
	 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
	 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 
	 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
	 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
	 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
	 * 
	 *************************************************************************/

	import flash.events.Event;
	import flash.net.LocalConnection;
	import flash.system.System;
	import flash.utils.setTimeout;
	
	import mx.core.Application;
	
	public class GarbageCollectionInitiator
	{
		/*************************************************************************
		 * The startGarbageCollection() function is the only publicly-accessible
		 * function provided by this class.  It will kick off two cycles of the
		 * garbage collection process using either the Flash System.gc() function
		 * if available or the "LocalConnection hack" to force GV if not.
		 * The first cycle will result in any objects that are eligible for GC
		 * based on their reference count to be freed.  It will also cause the first
		 * phase of the two-phase "mark and sweep" GC process to be executed.
		 * The second cycle will result in any objects that weren't marked in the
		 * first phase to be "swept" from memory.
		 * 
		 *************************************************************************/
		static public function startGarbageCollection():void
		{
			// Avoid multiple simultaneous gc cycles by ignoring requests while a
			// previous request is being executed.
			if ( _gcCount == -1 )
			{
				_gcCount = 0;
				// Push any existing enterframe handler off the call stack by creating a new one
				Application.application.addEventListener( Event.ENTER_FRAME, handleGarbageCollectionCycle );
			}
		}
		
		static private function handleGarbageCollectionCycle( event : Event ):void
		{
			executeGarbageCollection();
			if ( ++_gcCount > 1 )
			{
				// Remove the listener that we added at the start of the GC process before executing GC
				// the second time.
				Application.application.removeEventListener( Event.ENTER_FRAME, handleGarbageCollectionCycle );
				// Some AIR-only class instances can't be released using the enter frame listener.  
				// Release them via a timer timeout instead.
				setTimeout( handleLastGarbageCollectionCycle, 40 );
			}
		}
		
		static private function handleLastGarbageCollectionCycle():void
		{
			executeGarbageCollection();
			
			// Reset count now that the cycle has completed
			_gcCount = -1;
		}
		
		static private function executeGarbageCollection():void
		{
			// Make the request via system call if it is available.  Otherwise, perform a hack to accomplish the same thing.
			if ( flash.system.System.gc != null )
			{
				flash.system.System.gc();
			}
			else
			{
				try
				{
					new LocalConnection().connect('mcForceGC');
					new LocalConnection().connect('mcForceGC');
					// the GC will perform a full mark/sweep on the second call.
				}
				catch (e:*)
				{
					// TODO:  Add error handling and/or logging as appropriate for your application
				}
			}
		}
		
		static private var _gcCount : int = -1;
	}
}